<?php

namespace App\Http\Controllers;

use App\Exports\ArticlesExport;
use App\Models\Article;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class ArticleController extends BaseController
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $data = Article::orderBy('id','desc')->paginate(10);
        return view('admin.article.index',compact('data'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('admin.article.create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $params = $request->except(['_token', 'file']);
        $res = Article::create($params);
        if ($res) {
            return redirect(route("admin.article.index"));
        } else {
            return redirect(route("admin.article.index"))->withErrors("添加文章失败");
        }
    }

    /**
     * Display the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function edit(Request $request)
    {
        $id = $request->get('id');
        $data = Article::find($id);
        return view('admin.article.edit',compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param int $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $id = $request->get('id');
        $params = $request->except(['_token', 'file']);
        $res = Article::where('id',$id)->update($params);
        if ($res) {
            return redirect(route("admin.article.index"));
        } else {
            return redirect(route("admin.article.index"))->withErrors("添加文章失败");
        }
    }


    public function destroy(Request $request)
    {
        $id = $request->get('id');

         Article::destroy($id);

         return redirect(route('admin.article.index'));

    }

    /**
     * 本地图片上传
     */
    public function localUploadFile(Request $request)
    {
        $pic = $request->file('file')->store('', 'article');
        //dd($pic);
        $picPath = '/uploads/article/' . $pic;
        return $this->writeJson(0, ['pic' => $picPath], 'success');
    }

    public function export()
    {
        return Excel::download(new ArticlesExport, 'articles.xlsx');
    }
}
